package cn.tide.question2.dao;

import cn.tide.question2.domain.User;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserDao {
    public User findByNameAndPassword(String name, String password){
     User user = null;

        String sql = "select * from user where username= ? and password = password(?)";

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        try{
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/day1?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true","root","admin");
            PreparedStatement ps = connection.prepareStatement(sql);

            ps.setString(1, name);
            ps.setString(2, password);
            ResultSet rs =ps.executeQuery();

            if (rs.next()) {
                user = new User();
                int id = rs.getInt("id");
                user.setUsername(name);
                user.setPassword(password);
                user.setId(id);
            }

            ps.close();
            connection.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return user;
    }
}
